# --*-- coding:utf-8 --*--
# @Time : 2025/6/27 0:41
# @Author : Mark, Xu 
# @Email : 17521559996@163.com, wsxzy98@outlook.com
# @File : sale_order_line.py
# @Software : PyCharm, VScode

from odoo import models, fields, api


class gs_sale_order_line(models.Model):
    _inherit = 'sale.order.line'

    purchase_name = fields.Many2one('product.supplierinfo', string='供应商名称')
    new_serial_number = fields.Text('新编码', compute='_compute_new_serial_number', store=True)
    serial_number = fields.Text('序号', compute='_compute_serial_number', store=True)
    purchase_desc = fields.Text('采购描述',store=True)

    prodotto_id = fields.Char(string='产品')   # 对应product_id.default_code
    #prodotto_id = fields.Many2one('product.product', string='产品编号')
    descrizione = fields.Char(string='描述')   # 对应product_id.name

    purchase_qty_to_order = fields.Float(
        string="待采购数量",
        compute='_compute_purchase_qty_to_order',
        store=True  # 若不需要写入数据库可以去掉store
    )

    @api.depends('product_uom_qty', 'qty_delivered')
    def _compute_purchase_qty_to_order(self):
        for line in self:
            line.purchase_qty_to_order = max(line.product_uom_qty - line.qty_delivered, 0)

    @api.depends('product_template_id', 'product_template_id.new_variable')
    def _compute_new_serial_number(self):
        """
        计算新编码，递归查找直到找不到匹配的产品。
        """
        for line in self:
            # 初始的新编码（从product_template_id获取）
            serial_number = line.product_template_id.new_variable
            line.new_serial_number = line._find_last_serial_number(serial_number)

    @api.depends('order_id', 'order_id.order_line')
    def _compute_serial_number(self):
        for line in self:
            if line.product_id:
                number = 1
                for record in line.order_id.order_line:
                    if record.product_id:
                        record.serial_number = number
                        number += 1

    def _find_last_serial_number(self, serial_number):
        """
        递归查找新编码，直到找不到匹配的产品为止
        :param serial_number: 初始新编码
        :return: 最终找到的编码（或最后一个匹配的编码）
        """
        product_tmpl = self.env['product.template'].search([('default_code', '=', serial_number)], limit=1)

        if product_tmpl:
            next_serial_number = product_tmpl.new_variable
            if next_serial_number and next_serial_number != serial_number:
                return self._find_last_serial_number(next_serial_number)  # 递归查找
            else:
                return serial_number  # 没有找到新的编码，返回当前编码
        else:
            return serial_number  # 没有匹配的产品，返回当前编码

    @api.depends('product_id', 'company_id', 'currency_id', 'product_uom')
    def _compute_purchase_price(self):
        for record in self:
            if record.product_template_id:
                # 获取所有供应商价格
                supplier_infos = self.env['product.supplierinfo'].search([
                    ('product_tmpl_id', '=', record.product_template_id.id)
                ])

                # 初始化最低价格为 None
                min_price = None
                min_name = None

                # 遍历所有供应商价格，找到最低价格
                for supplier in supplier_infos:
                    if min_price is None or supplier.price < min_price:
                        min_price = supplier.price
                        min_name = supplier

                # 更新最低价格字段
                record.purchase_price = min_price
                record.purchase_name = min_name

    @api.onchange('purchase_name')
    def onchange_purchase_name(self):
        for record in self:
            if record.product_template_id:
                record.purchase_price = record.purchase_name.price

    @api.model
    def create(self, vals):
        """
        创建销售订单行时自动同步产品编号和描述
        """
        if vals.get('product_id'):
            prod = self.env['product.product'].browse(vals['product_id'])
            vals['prodotto_id'] = prod.default_code or ''
            vals['descrizione'] = prod.name or ''
        return super().create(vals)
    
    @api.onchange('product_id')
    def _onchange_product_fields(self):
        """
        当产品变更时自动同步产品编号和描述
        """
        for line in self:
            if line.product_id:
                line.prodotto_id = line.product_id.default_code or ''
                line.descrizione = line.product_id.name or ''
            else:
                line.prodotto_id = ''
                line.descrizione = ''
    
    def write(self, vals):
        """
        修改订单行时，如产品变化则同步编号和描述
        """
        res = super().write(vals)
        for line in self:
            if 'product_id' in vals and line.product_id:
                line.prodotto_id = line.product_id.default_code or ''
                line.descrizione = line.product_id.name or ''
        return res
